package vip.ola.pay.batchpay.yatoudf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.PayInterface;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchTrans;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_SUCCESS;

@RequestMapping("/api/yatoudf")
@Controller
public class YatoudfTransController extends BaseController {

    private static final MyLog _log = MyLog.getLog(YatoudfTransController.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestBody JSONObject object, HttpServletRequest request){
        _log.info("接收YatoudfTransController回调：" + object);
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        PayInterface payInterface = rpcCommonService.rpcPayInterfaceService.findByCode("yatoudf");
        String whiteIps=payInterface.getRemark();
        _log.info("请求ip为：" + clintIp+"  维护白名单ip： "+ whiteIps);
        if (StringUtils.isEmpty(whiteIps) || !Arrays.asList(whiteIps.split("\\,")).contains(clintIp)){
            _log.info( "IP[" + clintIp + "]不允许访问");
            return "ip fail";
        }
        String transOrderId = object.getString("out_order_no");
        TransOrder payOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        if(payOrder == null){
            return "order not exist!";
        }
        Long orderMoney = new BigDecimal(object.getString("money")).multiply(BigDecimal.valueOf(100)).longValue();
        if (orderMoney.longValue() != payOrder.getAmount().longValue()){
            return "money fail";
        }
        if (payOrder.getStatus() == TRANS_STATUS_SUCCESS || payOrder.getStatus() == TRANS_STATUS_COMPLETE) {
            return "SUCCESS";
        }
        AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        if (!"2".equals(object.getString("state")) ){
            _log.info("notify status is error,the mchOrderNo->{},status->{}:",transOrderId,object.getString("status"));
            return "status fail";
        }
        JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
        String retSign = object.getString("sign");
        String privateKey = accountParams.getString("privateKey");
        try {
            object.remove("sign");
            String sign = YatoudfTransService.getSign(object, privateKey);
            if (sign.equals(retSign)){
                String mchId = payPassageAccount.getPassageMchId();
                String queryUrl = accountParams.getString("queryUrl");
                Map<String, Object> obj = new HashMap<>();
                Long timeStamp = System.currentTimeMillis();
                obj.put("timestamp", timeStamp);
                obj.put("mch_id",mchId);
                obj.put("type",0);
                obj.put("out_order_no", transOrderId);
                String queryBytes = YatoudfTransService.getSign(obj, privateKey);
                obj.put("sign", queryBytes);
                _log.info("YatoudfTransController查询请求={}",JSONObject.toJSONString(obj));
                String respDetail = YatoudfTransService.call(queryUrl,obj);
                _log.info("YatoudfTransController-》订单查询明细返回={}",respDetail);
                if (StringUtils.isNotEmpty(respDetail)){
                    JSONObject resObj = JSON.parseObject(respDetail);
                    if ("0".equals(resObj.getString("code")))
                    {
                        String queryStatus = resObj.getJSONObject("data").getString("state");
                        if ("2".equals(queryStatus)){
                            int result =  rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId,"");
                            _log.info("更新订单状态为支付成功: result={}", result);
                            if(result == 1){
                                // 通知业务系统
                                baseNotify4MchTrans.doNotify(payOrder, true);
                                return "SUCCESS";
                            }
                        }else {
                            _log.info("query status is error,the mchOrderNo:"+transOrderId);
                            return "query error";
                        }
                    }else {
                        _log.info("query detail is error,the mchOrderNo:"+transOrderId);
                        return "query detail error";
                    }
                }else {
                    _log.error("订单查询异常，the mchorderno:" +transOrderId);
                    return "query error";
                }
            }else {
                _log.info("sign error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "verfiy fail";
        }
        return "fail!";
    }




}
